package com.blogs.security.login;

import com.blogs.common.utils.PasswordUtils;
import com.blogs.domain.db.SysUser;
import com.blogs.mapper.SysUserMapper;
import com.blogs.security.dto.SecurityUser;
import com.blogs.security.service.impl.CustomUserDetailsServiceImpl;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Description 自定义认证处理
 *
 * @author hubiao
 * @since 2020-09-27 23:21
 */
@Component
public class AdminAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private CustomUserDetailsServiceImpl userDetailsService;
    @Resource
    private SysUserMapper userDao;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取前端表单中输入后返回的用户名、密码
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        SecurityUser userInfo = (SecurityUser) userDetailsService.loadUserByUsername( userName );

        boolean isValid = PasswordUtils.isValidPassword( password, userInfo.getPassword(), userInfo.getCurrentUserInfo().getSalt() );
        // 验证密码
        if (!isValid) {
            throw new BadCredentialsException( "密码错误！" );
        }

        // 前后端分离情况下 处理逻辑...
        // 更新登录令牌 - 之后访问系统其它接口直接通过token认证用户权限...
        String token = PasswordUtils.encodePassword( System.currentTimeMillis() + userInfo.getCurrentUserInfo().getSalt(), userInfo.getCurrentUserInfo().getSalt() );
        SysUser user = userDao.getUserInfoById( userInfo.getCurrentUserInfo().getId() );
        user.setToken( token );
        userDao.updateUserInfo( user );
        userInfo.getCurrentUserInfo().setToken( token );
        return new UsernamePasswordAuthenticationToken( userInfo, password, userInfo.getAuthorities() );
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
